package cs.sasu.service.Impl;

import cs.sasu.mapper.CollegeMapper;
import cs.sasu.mapper.SystemUserMapper;
import cs.sasu.pojo.College;
import cs.sasu.pojo.SystemUser;
import cs.sasu.service.SystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class SystemUserServiceImpl implements SystemUserService {
    @Autowired
    private SystemUserMapper systemUserMapper;
    @Autowired
    private CollegeMapper collegeMapper;
    @Override
    public int save(SystemUser systemUser) {
        try {
            if(systemUser.getCollege().getCName() != null){
                List<College> colleges = collegeMapper.selectAll();
                Optional<College> first = colleges.stream().filter(college -> college.getCName().equals(systemUser.getCollege().getCName())).findFirst();
                first.ifPresent(systemUser::setCollege);
                int college_id = 0;
                if(!first.isEmpty()) {
                    college_id = collegeMapper.insertCollege(systemUser.getCollege());
                    systemUser.setCollege(new College(college_id, systemUser.getCollege().getCName()));

                }
            }
            return systemUserMapper.insert(systemUser);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public SystemUser get(String admin) {
        try {
            return systemUserMapper.getUserById(admin);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int update(SystemUser systemUser) {
        try {
            return systemUserMapper.update(systemUser);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int delete(String name) {
        try {
            return systemUserMapper.delete(name);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int remove(String name) {
        try {
            return systemUserMapper.remove(name);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
